import {
  login,
  logout,
  getUserInfo,
  getMessage,
  getContentByMsgId,
  hasRead,
  removeReaded,
  restoreTrash
  // getUnreadCount
} from '@/api/user'
import routes from '@/router/routers'
import { setToken, getToken, setMerchantId, getMerchantId, setUserId, getUserId, setUserName, getUserName, setPhoneNumber, getPhoneNumber, setLoginTime, getLoginTime,
  getLastLoginTime, setLastLoginTime, getLoginIp, setLoginIp, getLoginAdress, setLoginAdress, setOrgName, getOrgName, setOrgId, getOrgId, setOrgType, getOrgType } from '@/libs/util'
import { module } from '@/libs/module.js'
export default {
  state: {
    userName: getUserName(),
    userId: getUserId(),
    loginTime: getLoginTime(),
    lastLoginTime: getLastLoginTime(),
    loginIp: getLoginIp(),
    loginAdress: getLoginAdress(),
    orgName: getOrgName(),
    orgId: getOrgId(),
    orgType: getOrgType(),
    avatorImgPath: '',
    phoneNumber: getPhoneNumber(),
    token: getToken(),
    merchantId: getMerchantId(),
    userRes: [], // 所有当前系统资源权限
    module: [], // 拥有的模块
    curModule: null,
    hasGetInfo: false,
    unreadCount: 0,
    messageUnreadList: [],
    messageReadedList: [],
    messageTrashList: [],
    messageContentStore: {}
  },
  mutations: {
    setAvator (state, avatorPath) {
      state.avatorImgPath = avatorPath
    },
    setUserId (state, id) {
      state.userId = id
      setUserId(id)
    },
    setUserName (state, name) {
      state.userName = name
      setUserName(name)
    },
    setPhoneNumber (state, num) {
      state.phoneNumber = num
      setPhoneNumber(num)
    },
    setLoginTime (state, time) {
      state.loginTime = time
      setLoginTime(time)
    },
    setLastLoginTime (state, time) {
      state.lastLoginTime = time
      setLastLoginTime(time)
    },
    setLoginIp (state, ip) {
      state.loginIp = ip
      setLoginIp(ip)
    },
    setLoginAdress (state, adress) {
      state.loginAdress = adress
      setLoginAdress(adress)
    },
    setOrgName (state, name) {
      state.orgName = name
      setOrgName(name)
    },
    setOrgId (state, orgId) {
      state.orgId = orgId
      setOrgId(orgId)
    },
    setOrgType (state, orgType) {
      state.orgType = orgType
      setOrgType(orgType)
    },
    setModule (state, module) {
      state.module = module
    },
    setToken (state, token) {
      state.token = token
      setToken(token)
    },
    setMerchantId (state, merchantId) {
      state.merchantId = merchantId
      setMerchantId(merchantId)
    },
    setUserRes (state, res) {
      state.userRes = res
    },
    setCurModule (state, cur) {
      state.curModule = cur
    },
    setHasGetInfo (state, status) {
      state.hasGetInfo = status
    },
    setMessageCount (state, count) {
      state.unreadCount = count
    },
    setMessageUnreadList (state, list) {
      state.messageUnreadList = list
    },
    setMessageReadedList (state, list) {
      state.messageReadedList = list
    },
    setMessageTrashList (state, list) {
      state.messageTrashList = list
    },
    updateMessageContentStore (state, { msg_id, content }) {
      state.messageContentStore[msg_id] = content
    },
    moveMsg (state, { from, to, msg_id }) {
      const index = state[from].findIndex(_ => _.msg_id === msg_id)
      const msgItem = state[from].splice(index, 1)[0]
      msgItem.loading = false
      state[to].unshift(msgItem)
    }
  },
  getters: {
    messageUnreadCount: state => state.messageUnreadList.length,
    messageReadedCount: state => state.messageReadedList.length,
    messageTrashCount: state => state.messageTrashList.length
  },
  actions: {
    // 登录
    handleLogin ({ commit }, { loginName, password }) {
      return new Promise((resolve, reject) => {
        login({
          loginName,
          password
        }).then(res => {
          if (res.data.status === 200) {
            commit('setToken', res.data.data.token)
            commit('setMerchantId', res.data.data.merchantId)
            commit('setUserId', res.data.data.id)
            commit('setUserName', res.data.data.username)
            commit('setPhoneNumber', res.data.data.phoneNumber)
            commit('setLoginTime', res.data.data.loginTime)
            commit('setLastLoginTime', res.data.data.lastLoginTime)
            commit('setLoginIp', res.data.data.loginIp)
            commit('setLoginAdress', res.data.data.loginAdress)
            commit('setOrgId', res.data.data.orgId)
            commit('setOrgType', res.data.data.orgType)
            commit('setOrgName', res.data.data.orgName)
            commit('setAvator', '')
          }
          resolve(res.data)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 退出登录
    handleLogOut ({ state, commit }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('setToken', '')
          commit('setMerchantId', '')
          commit('setUserId', '')
          commit('setUserName', '')
          commit('setPhoneNumber', '')
          commit('setLoginTime', '')
          commit('setLastLoginTime', '')
          commit('setLoginIp', '')
          commit('setLoginAdress', '')
          commit('setOrgId', '')
          commit('setOrgType', '')
          commit('setOrgName', '')
          commit('setAvator', '')
          resolve()
        }).catch(err => {
          reject(err)
        })
      })
    },
    // 获取用户相关信息
    getUserInfo ({ state, commit }) {
      return new Promise((resolve, reject) => {
        try {
          getUserInfo({
            merchantId: state.merchantId,
            id: state.userId,
            orgId: state.orgId
          }).then(res => {
            const data = res.data
            if (data.status === 200) {
              // moms为商户管理后台标识  过滤出当前系统权限
              let resList = data.data.filter(item => {
                return item.perms.indexOf('moms') === 0
              })
              commit('setUserRes', resList)
              // 从当前系统权限中 过滤出模块权限
              let hasModule = module.filter(item => {
                let flag = false
                if (typeof item.msn === 'string') {
                  resList.forEach(res => {
                    if (res.perms.indexOf(item.msn) === 0) {
                      flag = true
                    }
                  })
                } else {
                  item.msn.forEach(sn => {
                    resList.forEach(res => {
                      if (res.perms.indexOf(sn) === 0) {
                        flag = true
                      }
                    })
                  })
                }
                return flag
              })
              // 模块权限中添加菜单权限
              hasModule.forEach(module => {
                module.menu = []
                routes.forEach(route => {
                  if (route.meta.sn) {
                    if (typeof module.msn === 'string') {
                      if (route.meta.sn.indexOf(module.msn) !== -1) {
                        let moduleRoute = {
                          ...route,
                          children: []
                        }
                        if (route.children.length > 0) {
                          route.children.forEach(croute => {
                            if (croute.meta.sn) {
                              resList.forEach(res => {
                                if (res.perms.trim() === croute.meta.sn) {
                                  moduleRoute.children.push(croute)
                                }
                              })
                            }
                          })
                        }
                        if (route.meta.sn.indexOf('|') === -1) {
                          if (moduleRoute.children.filter(item => item.meta.sn === route.meta.sn).length > 0) {
                            module.menu.push(moduleRoute)
                          }
                        } else {
                          let routeSn = route.meta.sn.split('|')
                          let ret = false
                          routeSn.forEach(sn => {
                            if (moduleRoute.children.filter(item => item.meta.sn === sn).length > 0) {
                              ret = true
                            }
                          })
                          if (ret) {
                            module.menu.push(moduleRoute)
                          }
                        }
                      }
                    } else {
                      let flag = false
                      module.msn.forEach(snItem => {
                        if (route.meta.sn.indexOf(snItem) !== -1) {
                          flag = true
                        }
                      })
                      if (flag) {
                        let moduleRoute = {
                          ...route,
                          children: []
                        }
                        if (route.children.length > 0) {
                          route.children.forEach(croute => {
                            if (croute.meta.sn) {
                              resList.forEach(res => {
                                if (res.perms.trim() === croute.meta.sn) {
                                  moduleRoute.children.push(croute)
                                }
                              })
                            }
                          })
                        }
                        if (route.meta.sn.indexOf('|') === -1) {
                          if (moduleRoute.children.filter(item => item.meta.sn === route.meta.sn).length > 0) {
                            module.menu.push(moduleRoute)
                          }
                        } else {
                          let routeSn = route.meta.sn.split('|')
                          let ret = false
                          routeSn.forEach(sn => {
                            if (moduleRoute.children.filter(item => item.meta.sn === sn).length > 0) {
                              ret = true
                            }
                          })
                          if (ret) {
                            module.menu.push(moduleRoute)
                          }
                        }
                      }
                    }
                  }
                })
                if (module.menu.length) {
                  if (module.menu[0].children.length > 0) {
                    module.redirect = module.menu[0].children[0].name
                  } else {
                    module.redirect = module.menu[0].name
                  }
                }
              })
              commit('setModule', hasModule)
              commit('setHasGetInfo', true)
            }
            resolve(data)
          }).catch(err => {
            reject(err)
          })
        } catch (error) {
          reject(error)
        }
      })
    },
    // 此方法用来获取未读消息条数，接口只返回数值，不返回消息列表
    getUnreadMessageCount ({ state, commit }) {
      // getUnreadCount().then(res => {
      //   const { data } = res
      //   commit('setMessageCount', data)
      // })
    },
    // 获取消息列表，其中包含未读、已读、回收站三个列表
    getMessageList ({ state, commit }) {
      return new Promise((resolve, reject) => {
        getMessage().then(res => {
          const { unread, readed, trash } = res.data
          commit('setMessageUnreadList', unread.sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          commit('setMessageReadedList', readed.map(_ => {
            _.loading = false
            return _
          }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          commit('setMessageTrashList', trash.map(_ => {
            _.loading = false
            return _
          }).sort((a, b) => new Date(b.create_time) - new Date(a.create_time)))
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 根据当前点击的消息的id获取内容
    getContentByMsgId ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        let contentItem = state.messageContentStore[msg_id]
        if (contentItem) {
          resolve(contentItem)
        } else {
          getContentByMsgId(msg_id).then(res => {
            const content = res.data
            commit('updateMessageContentStore', { msg_id, content })
            resolve(content)
          })
        }
      })
    },
    // 把一个未读消息标记为已读
    hasRead ({ state, commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        hasRead(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageUnreadList',
            to: 'messageReadedList',
            msg_id
          })
          commit('setMessageCount', state.unreadCount - 1)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 删除一个已读消息到回收站
    removeReaded ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        removeReaded(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageReadedList',
            to: 'messageTrashList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 还原一个已删除消息到已读消息
    restoreTrash ({ commit }, { msg_id }) {
      return new Promise((resolve, reject) => {
        restoreTrash(msg_id).then(() => {
          commit('moveMsg', {
            from: 'messageTrashList',
            to: 'messageReadedList',
            msg_id
          })
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}
